package com.yang.intercepter;

import com.yang.domain.User;
import com.yang.handler.UserThreadLocal;
import com.yang.mapper.UserMapper;
import com.yang.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 * @Author: 不是菜鸡爱编程
 * @Date: 2024/02/17
 * @Description：@see HandlerInterceptor
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 先获取请求头里的token
        String token = request.getHeader("Authorization");
        // token判空
        if(StringUtils.isEmpty(token)){
            log.error("当前请求路径为:{}",request.getRequestURL());
            throw new RuntimeException("未登录，请登录后重试!");
        }
        // token解析是否成功，若成功，则放行；否则，不放行
        String userIdByToken = JwtUtil.getUserIdByToken(token);
        User user = userMapper.selectById(userIdByToken);
        // 将用户信息存入LocalThreadLocal
        UserThreadLocal.put(user);
        // 返回值代表是否放行
        return true;
    }

    /**
     * 删除用户信息，防止内存泄漏
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
